package com.yun.baymax.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.yun.baymax.R;
import com.yun.baymax.bean.adapter.BudgetInfo;
import com.yun.baymax.utils.ToastUtils;
import com.yun.lib.fragment.BaseFragment;
import com.yun.lib.utils.KeyBoardUtils;
import com.yun.lib.utils.MathUtil;
import com.yun.lib.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class BudgetFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private Context mContext;
    private ListView listView;
    private ItemListAdapter adapter;
    private EditText diaBank;
    private EditText diaTotal;
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    private LayoutInflater inflater;
    private TextView debt;
    private SwipeRefreshLayout refreshLayout;

    @Override
    protected int setLayoutResourceId() {
        mContext = getContext();
        return R.layout.activity_bill;
    }

    @Override
    protected void initViews(Bundle savedInstanceState, View view, LayoutInflater inflater) {
        listView = (ListView) view.findViewById(R.id.list_view);
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
        refreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.text_color_blue, R.color.voucher_color_red);
        refreshLayout.setOnRefreshListener(this);
        init(inflater);
    }


    private void init(LayoutInflater inflater) {
        this.inflater = inflater;
        View footView = inflater.inflate(R.layout.foot_view, null);
        View headView = inflater.inflate(R.layout.listview_head, null);
        TextView footText = (TextView) footView.findViewById(R.id.foot_text);
        footText.setText("添加预算");
        debt = (TextView) headView.findViewById(R.id.debt);
        listView.addHeaderView(headView);
        listView.addFooterView(footView);

        View add = footView.findViewById(R.id.add_bill);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createEditDialog(true, null);
            }
        });

        adapter = new ItemListAdapter(mContext);
        listView.setAdapter(adapter);
        fetchData();
    }

    private void fetchData() {
        refreshLayout.setRefreshing(true);
        BmobQuery<BudgetInfo> billQuery = new BmobQuery<>();
        billQuery.addWhereEqualTo("author", BmobUser.getCurrentUser().getUsername());
        billQuery.findObjects(new FindListener<BudgetInfo>() {
            @Override
            public void done(List<BudgetInfo> list, BmobException e) {
                refreshLayout.setRefreshing(false);
                if (e == null) {
                    adapter.setDatas(list);
                } else {
                    ToastUtils.showShortToast("获取数据失败");
                }
            }
        });

    }

    private void createEditDialog(final boolean add, final BudgetInfo budgetInfo) {
        View dialog = inflater.inflate(R.layout.dialog_add_budget, null);//(ViewGroup) findViewById(R.id.dialog)
        diaBank = (EditText) dialog.findViewById(R.id.et_bank);
        diaTotal = (EditText) dialog.findViewById(R.id.et_total);

        builder = new AlertDialog.Builder(mContext);
        builder.setTitle(add ? "添加预算" : "修改预算");
        builder.setView(dialog);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String name = diaBank.getText().toString();
                double total = StringUtils.getDoubleNoNull(diaTotal.getText().toString());

                if (TextUtils.isEmpty(diaBank.getText().toString())) {
                    return;
                }
                if (add) {
                    BudgetInfo BudgetInfo = new BudgetInfo(name, total);
                    BudgetInfo.setAuthor(BmobUser.getCurrentUser().getUsername());
                    saveUP(BudgetInfo);
                    adapter.addDatas(BudgetInfo);
                } else {
                    budgetInfo.saveAll(name, total);
                    updateUP(budgetInfo);
                    adapter.updateDatas(budgetInfo, name, total);
                }
            }
        });
        alertDialog = builder.create();
        alertDialog.show();
    }

    //上传增加或修改的数据
    private void saveUP(BudgetInfo BudgetInfo) {
        BudgetInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e != null)
                    ToastUtils.showShortToast(e.getMessage());
                else
                    ToastUtils.showShortToast("添加成功");
            }
        });
    }

    //上传修改的数据
    private void updateUP(BudgetInfo BudgetInfo) {

        BudgetInfo.update(BudgetInfo.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                } else ToastUtils.showShortToast(e.getMessage());
            }
        });
    }

    //删
    private void deleteUP(BudgetInfo data) {
        data.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null)
                    ToastUtils.showShortToast("删除成功");
                else ToastUtils.showShortToast(e.getMessage());
            }
        });
    }

    @Override
    public void onRefresh() {
        fetchData();
    }

    public class ItemListAdapter extends BaseAdapter {

        private List<BudgetInfo> datas = new ArrayList<>();

        private Context context;
        private LayoutInflater layoutInflater;
        private View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewHolder holder = (ViewHolder) v.getTag();
                if (holder == null || holder.position >= datas.size())
                    return;
                onItemClick(v, datas.get(holder.position), holder, holder.position);
            }
        };

        public ItemListAdapter(Context context) {
            this.context = context;
            this.layoutInflater = LayoutInflater.from(context);
        }

        public ItemListAdapter(Context context, List<BudgetInfo> datas) {
            this.context = context;
            this.layoutInflater = LayoutInflater.from(context);
            this.datas = datas;
            setDebt();
        }

        public void addDatas(BudgetInfo data) {
            datas.add(data);
            setDebt();
            notifyDataSetChanged();
        }

        public void updateDatas(BudgetInfo BudgetInfo, String name, double total) {
            setDebt();
            notifyDataSetChanged();
        }

        public void setDatas(List<BudgetInfo> datas) {
            this.datas = datas;
            setDebt();
            notifyDataSetChanged();
        }

        public void setDebt() {
            double debtMoney = 0;
            for (int i = 0; i < datas.size(); i++) {
                debtMoney = MathUtil.add(debtMoney, datas.get(i).getTotal());
            }
            debt.setText(String.valueOf(debtMoney));
        }

        @Override
        public int getCount() {
            return datas == null ? 0 : datas.size();
        }

        @Override
        public BudgetInfo getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.item_budget_list, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.position = position;
            initHolderViews(getItem(position), holder, position);
            convertView.setOnClickListener(onItemClickListener);
            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    deleteItem(getItem(position));
                    return false;
                }
            });
            return convertView;
        }

        private void initHolderViews(final BudgetInfo data, final ViewHolder holder, final int position) {
            holder.itemName.setText(data.getName());
            holder.total.setText(String.valueOf(data.getTotal()));

            holder.total.setOnClickListener(new View.OnClickListener() {
                private EditText editText;

                @Override
                public void onClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("修改预算");
                    View dialogView = layoutInflater.inflate(R.layout.edit_dialog, null);
                    editText = (EditText) dialogView.findViewById(R.id.edit_text);
                    editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                    builder.setView(dialogView);
                    builder.setPositiveButton("减少预算", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            double result = MathUtil.sub(data.getTotal(), StringUtils.getDoubleNoNull(editText.getText().toString()));
                            data.setTotal(result);
                            setDebt();
                            updateUP(data);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    builder.setNegativeButton("增加预算", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            double result = MathUtil.add(data.getTotal(), StringUtils.getDoubleNoNull(editText.getText().toString()));
                            data.setTotal(result);
                            setDebt();
                            updateUP(data);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                    KeyBoardUtils.openKeybord(diaBank, mContext);
                    alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            KeyBoardUtils.closeKeybord(getActivity());
                        }
                    });
                }
            });
        }

        private void deleteItem(final BudgetInfo data) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(data.getName());
            builder.setMessage("确认删除？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    datas.remove(data);
                    setDebt();
                    deleteUP(data);
                    adapter.notifyDataSetChanged();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }

        private void onItemClick(View convertView, final BudgetInfo data, ViewHolder holder, int position) {
            createEditDialog(false, data);
            diaBank.setText(data.getName());
            diaTotal.setText("" + data.getTotal());
        }

        protected class ViewHolder {
            private TextView itemName;
            private TextView total;
            private int position;

            public ViewHolder(View view) {
                itemName = (TextView) view.findViewById(R.id.item_name);
                total = (TextView) view.findViewById(R.id.total);
            }
        }
    }
}
